package com.chooseCourses.servlet.admin;

import com.chooseCourses.dao.BaseDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet(urlPatterns = "/AdminModify")
public class AdminModify extends HttpServlet {
    public AdminModify() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().append("Served at: ").append(req.getContextPath());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        System.out.println(req.getParameter("userId"));
//        System.out.println(req.getAttribute("userId"));
        int userId = Integer.parseInt(req.getParameter("userId"));
        String userName = req.getParameter("userName");
        String oldPw = req.getParameter("oldPw");
        String newPw = req.getParameter("newPw");
        System.out.println("userId="+userId);
        System.out.println("userName="+userName);
        System.out.println("oldPw="+oldPw);
        System.out.println("newPw="+newPw);
        BaseDao baseDao = new BaseDao();
        String sql = "select * from admin where Id='" + userId + "' and loginpassword='" + oldPw + "'";
        String sql1 = "update admin set loginpassword = ? where id = ?";
        ResultSet resultSet;
        PreparedStatement ps;
        try {
            ps=baseDao.getConnection().prepareStatement(sql);
            resultSet=ps.executeQuery();
            if (resultSet.next()) {
                ps=baseDao.getConnection().prepareStatement(sql1);
                ps.setString(1, newPw);
                ps.setInt(2, userId);
                ps.executeUpdate();//执行更新
                PrintWriter out = resp.getWriter();
                resp.sendRedirect("admin/adminMes.jsp?userName=" + userName + "&userId=" + userId);
            }else {
                PrintWriter out = resp.getWriter();
                resp.sendRedirect("admin/adminEdi.jsp?userName=" + userName + "&userId=" + userId + "&message=" + "1");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        doGet(req,resp);
    }
}
